import sys
import os
from collections import deque
from datetime import datetime

import torch
import torch.nn as nn
import torch.optim as optim
# import torch.nn.functional as F
import random
import math
import numpy as np

import pandas as pd
import json

from util.loguru_util import myLogger

from train_all_offline import  process_cdudata_neural, process_longrundata_neural, process_fsudata_neural
from util.FIFO_Stack import FIFO_Stack
from all_config import dryFan_action_space, cduValve1_action_space
from choose_best_action import choose_best_action



all_stack = FIFO_Stack()

count = 0

# 设置默认值，有问题再改
last_longrun_config_dict = {
    "dryValve1": 50,
    "dryValve2": 50,
    "dryValve3": 50,
    "dryValve4": 50,
    "dryValve5": 50,
    "pumpPump": 50,
    "pumpBypassValve": 50}
last_cdu_config_dict = {'cduValve1': 50}

######################## 状态参数####################


need_control_temp = 40

########################环境状态参数###########################
from all_config import need_all_key



def train_all_online(input_data):
    global  last_cdu_config_dict, last_longrun_config_dict
    #################################### 数据预处理
    # input data
    ####################################
    global count
    if 1:
    # todo 这里的if也需要修改
    #try:

        # myLogger.info(f"len(longrun_data): {len(longrun_data)}")
        # myLogger.info(f'longrun_data: {longrun_data}')
        longrun_data = json.loads(input_data[0])
        cdu_data = json.loads(input_data[1])
        fsu_data = json.loads(input_data[2])

        # 这里是读取所有状态值，并进行筛选
        # 这里对重要状态进行筛选,带有neural的是用于进行智能的状态值的输入（离线训练）
        #longrun_sorted_dict = process_longrundata(longrun_data)
        longrun_sorted_dict_neural = process_longrundata_neural(longrun_data)
        # myLogger.info(flen(longrun_sorted_dict): {len(longrun_sorted_dict)}")
        # myLogger.info(f'longrun_sorted_dict: {longrun_sorted_dict}')
        #cdu_sorted_dict = process_cdudata(cdu_data)
        cdu_sorted_dict_neural = process_cdudata_neural(cdu_data)

        #fsu_sorted_dict = process_fsudata(fsu_data)
        fsu_sorted_dict_neural = process_fsudata_neural(fsu_data)


        #!!!!!!!!!!!!!!!!!!!!!!!
        ############# 此处为环境状态组成的字典############################
        all_sorted_dict = {**longrun_sorted_dict_neural, **cdu_sorted_dict_neural, **fsu_sorted_dict_neural}
        ############# 此处为环境状态组成的字典############################
        # !!!!!!!!!!!!!!!!!!!!!!!

        all_pddata = pd.Series(all_sorted_dict)
        all_stack.data_to_stack(all_pddata)
        all_previous, all_current = all_stack.transaction_data()
        ###########################################################################################################
        # 当程序液冷系统开始运行，则进行训练
        if (all_current['pduEnergy'] - all_previous['pduEnergy']) > 0:

            myLogger.info(f"count******************************:{count}")

################################################在线推理部分##############################################
            # 推理部分
            all_action = choose_best_action(dryFan_action_space, cduValve1_action_space, all_sorted_dict,need_all_key=need_all_key)
            dryfan1 = all_action[0]
            dryfan2 = all_action[1]
            dryfan3 = all_action[2]
            dryfan4 = all_action[3]
            dryfan5 = all_action[4]
            cdu_valve = all_action[5]


            myLogger.info(f'推理部分########################################')
            myLogger.info(f'dryfan: {dryfan1, dryfan2, dryfan3, dryfan4, dryfan5}')
            myLogger.info(f'cdu_valve: {cdu_valve}')




#########################################################################################################################
#####################################此处是人工主动干预的代码##############################################

            # 安全保护机制
            # if all_current['cduTso'] > 55:
            #     myLogger.info(f"温度即将到达阈值，快速降温")
            #     dryfan1 = 80
            #     dryfan2 = 80
            #     dryfan3 = 80
            #     dryfan4 = 80
            #     dryfan5 = 80
            #     cdu_valve = 80
            # elif all_current['cduTso'] < 35:
            #     myLogger.info(f"温度过低，快速升温")
            #     dryfan1 = 0
            #     dryfan2 = 0
            #     dryfan3 = 0
            #     dryfan4 = 0
            #     dryfan5 = 0
            #     cdu_valve = 5

            # 参数安全检测
            def check_fan_range(fan_value):
                if fan_value <= 0:
                    return 0
                elif fan_value >= 90:
                    return 90
                return fan_value

            def check_valve_range(valve_value):
                if valve_value <= 5:
                    return 5
                elif valve_value >= 95:
                    return 95
                return valve_value

            dryfan1 = check_fan_range(dryfan1)
            dryfan2 = check_fan_range(dryfan2)
            dryfan3 = check_fan_range(dryfan3)
            dryfan4 = check_fan_range(dryfan4)
            dryfan5 = check_fan_range(dryfan5)
            cdu_valve = check_valve_range(cdu_valve)







#######################################################################################################################

            # !!这里组装参数的地方!!#
            cdu_config_dict = {"cduValve1":cdu_valve, "cduPump1": 50}
            longrun_config_dict = {
                                   'dryValve1': dryfan1,
                                   'dryValve2': dryfan2,
                                   'dryValve3': dryfan3,
                                   'dryValve4': dryfan4,
                                   'dryValve5': dryfan5,

                                   'pumpPump': 47,
                                    "pumpBypassValve":50
                                    }

            last_cdu_config_dict = cdu_config_dict
            last_longrun_config_dict = longrun_config_dict

            count += 1
            return longrun_config_dict, cdu_config_dict
        else:
            myLogger.info(f"last_longrun_config_dict: {last_longrun_config_dict}")
            myLogger.info(f"last_cdu_config_dict: {last_cdu_config_dict}")
            return last_longrun_config_dict, last_cdu_config_dict

############################################# 模型保存 ################################################################



